import ProTable from '@ant-design/pro-table';
import { Form } from '@ant-design/compatible';
import { Button, message, DatePicker, Select } from 'antd';
import React, { useState, useRef, useEffect, useCallback } from 'react';
import '@ant-design/compatible/assets/index.css';
import { paydetail, exportPaybookdetail } from '../service';
import { useRequest } from '@umijs/hooks';
import styles from './index.less';
import moment from 'moment';
import AuthComponent from '@/components/Authorized/AuthComponent';

const { Option } = Select;
let hiddenData = null

const PayDetail = () => {

  const actionRef = useRef();
  const ref = useRef();

  // 支付宝、微信、现金、银联、总和
  const [summaryData, setSummaryData] = useState({})
  // 存储搜索条件
  const [searchParams, setSearchParams] = useState('')
  // 是否有表格数据
  const [exportFlag, handleExportFlag] = useState('')
  // 计算高度
  const [height, controlH] = useState(300);
  // 表格是否折叠
  const [isCollapse, controlC] = useState(true);
  // 是否为第一次加载
  const [firstLoadDate, setFirstLoadDate] = useState(true);

  /**
   * 导出
   */
  const handleExport = () => {
    if (!exportFlag) {
      message.warning('表格数据为空')
      return false
    }
    const hide = message.loading('正在导出');
    let res = exportPaybookdetail(searchParams).then(res => {
      let blob = new Blob([res], {
        type: 'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      })
      let elink = document.createElement('a')
      let time = moment(Date.now()).format('YYYY-MM-DD HH_ss_mm')
      elink.download = '异常行李支付明细报表' + time + '.xls'
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      document.body.removeChild(elink)
      hide();
      message.success('导出成功');
    }).catch(err => {
      console.log(err)
    });
  }

  // 搜索
  const beforeSearchSubmit = useCallback(params => {
    params['payStartTime'] = params.payStartTime ? params.payStartTime.format('YYYY-MM-DD') : '';
    params['payEndTime'] = params.payEndTime ? params.payEndTime.format('YYYY-MM-DD') : '';
    if (!isCollapse) {
      if (event.target.querySelector('span').innerText === '重 置') {
        ref.current.setFieldsValue({
          payStartTime: moment(),
          payEndTime: moment()
        })
      }
      setSearchParams(params)
      return params
    } else {
      if (event.target.querySelector('span').innerText === '查 询') {
        if (Object.keys(params).indexOf('payStartTime') === -1) {
          params.payStartTime = ''
        }
        if (Object.keys(params).indexOf('payEndTime') === -1) {
          params.payEndTime = ''
        }
        setSearchParams({ ...hiddenData, ...params })
        return { ...hiddenData, ...params }
      } else if (event.target.querySelector('span').innerText === '重 置') {
        ref.current.setFieldsValue({
          payStartTime: moment(),
          payEndTime: moment()
        })
        hiddenData = null
        setSearchParams(params)
        return params
      }
    }
  }, [isCollapse]);

  // 切换清空搜索
  useEffect(() => {
    hiddenData = null
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  useEffect(() => {
    if (isCollapse) {
      controlH(document.body.clientHeight - 505);
    } else {
      controlH(document.body.clientHeight - 555);
    }
  }, [isCollapse])


  const columns = [
    {
      title: '转账请求(起始)时间',
      dataIndex: 'payStartTime',
      renderFormItem: (_, { onChange, value, ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            onChange={onChange}
            format={format}
            value={value}
            {...rest}
          />
        );
      },
      hideInTable: true
    },
    {
      title: '转账请求(结束)时间',
      dataIndex: 'payEndTime',
      renderFormItem: (_, { onChange, value, ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            onChange={onChange}
            format={format}
            value={value}
            {...rest}
          />
        );
      },
      hideInTable: true
    },
    {
      title: '支付日期',
      dataIndex: 'payDate',
      fixed: 'left',
      width: 120,
      hideInSearch: true
    },
    {
      title: '支付时间',
      dataIndex: 'payTime',
      fixed: 'left',
      width: 120,
      hideInSearch: true
    },
    {
      title: '支付业务（申领）单号',
      dataIndex: 'applyCode',
      fixed: 'left',
      width: 180
    },
    {
      title: '支付金额（单位：元）',
      dataIndex: 'transAmount',
      width: 180,
      hideInSearch: true
    },
    {
      title: '支付方式',
      dataIndex: 'payType',
      width: 90,
      renderFormItem: (_, { onChange, value }) => {
        return (
          <Select
            mode="multiple"
            allowClear={true}
            showSearch
            placeholder='请选择'
            filterOption={true}
            optionFilterProp="children"
            onChange={onChange}
            value={value ? value : undefined}
          >
            <Option key='0'>微信</Option>
            <Option key='1'>银联</Option>
            <Option key='2'>支付宝</Option>
            <Option key='3'>优惠券</Option>
            <Option key='4'>现金</Option>
          </Select>
        );
      }
    },
    {
      title: '户名',
      dataIndex: 'accountName',
      width: 120,
      hideInSearch: true
    },
    {
      title: '开户银行',
      dataIndex: 'depositBank',
      width: 120,
      hideInSearch: true
    },
    {
      title: '账号',
      dataIndex: 'applyAccount',
      width: 120,
      hideInSearch: true,
      ellipsis: true
    },
    {
      title: '支付流水号',
      dataIndex: 'returnOrderNo',
      width: 120,
      hideInSearch: true,
      ellipsis: true
    },
    {
      title: '支付状态',
      dataIndex: 'payStatus',
      width: 90,
      hideInSearch: true
    },
  ];

  return (
    <div>
      <ProTable
        actionRef={actionRef}
        formRef={ref}
        rowKey="id"
        className={styles.payDetail}
        headerTitle={
          <div>
            <span style={{ paddingRight: 10, fontWeight: "bold", color: "#000" }}>支付明细表</span>
          </div>
        }
        options={{ density: false, fullScreen: true, reload:false, setting: true }}
        beforeSearchSubmit={beforeSearchSubmit}
        search={{
          span: 8,
          onCollapse: val => {
            controlC(val);
            if (!val && hiddenData) {
              ref.current.setFieldsValue({
                applyCode: hiddenData.applyCode,
                payType: hiddenData.payType
              })
            } else {
              hiddenData = ref.current.getFieldsValue()
            }
          }
        }}
        toolBarRender={(action, { selectedRows }) => [
          <AuthComponent authCode="banksearchSystem.payDetail.export">
            <Button icon="download" type="primary" onClick={handleExport} size="small">
              导出
            </Button>
          </AuthComponent>
        ]}
        postData={(data) => {
          if (data.transRecord.data.length === 0) {
            handleExportFlag(false)
          } else {
            handleExportFlag(true)
          }
          setSummaryData(data.summaryMoney)
          return data.transRecord.data
        }}
        request={params => {
          if (!params['payStartTime'] && !params['payEndTime'] && firstLoadDate) {
            setFirstLoadDate(false)
            params['payStartTime'] = moment().format('YYYY-MM-DD')
            params['payEndTime'] = moment().format('YYYY-MM-DD')

            ref.current.setFieldsValue({
              payStartTime: moment(),
              payEndTime: moment()
            })
          }
          return paydetail(params)
        }}
        columns={columns}
        footer={() => {
          return <div style={{ textAlign: 'right' }}>
            <span>微信: {summaryData && summaryData.wxMoney}</span> &nbsp;&nbsp;
            <span>支付宝: {summaryData && summaryData.alipayMoney}</span>&nbsp;&nbsp;
            <span>银联: {summaryData && summaryData.unionpayMoney}</span>&nbsp;&nbsp;
            <span>现金: {summaryData && summaryData.cashMoney}</span>&nbsp;&nbsp;
            <span>总和: {summaryData && summaryData.allMoney}</span>&nbsp;&nbsp;
          </div>
        }}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `第${range[0]}-${range[1]}条 共 ${total} 项`,
          defaultPageSize: 20,
          pageSizeOptions: ['20', '30', '40']
        }}
        scroll={{ x: 1300, y: height }}
      />
    </div>
  );
};

export default Form.create()(PayDetail);
